// src/services/opcua_webapi.rs

use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::RwLock;
use warp::Filter;
use serde::{Deserialize, Serialize};
use anyhow::{Result, anyhow};
use log::{info, warn, error, debug};

use crate::{
    interfaces::SemanticConverter,
    models::{
        ConversionRequest,
        ConversionResult,
        ConversionStatus,
        ValidationRequest,
        ValidationResult,
        BatchConversionRequest,
        BatchConversionResult,
        ServiceInfo,
        HealthStatus,
        PerformanceMetrics,
    },
    config::Settings,
};

/// OPC UA Web API 服务
/// 提供RESTful API接口，对外暴露语义转换功能
pub struct OPCUAWebAPIService<C>
where
    C: SemanticConverter + Send + Sync + 'static,
{
    /// 语义转换器
    converter: Arc<C>,
    /// 服务配置
    config: Settings,
    /// 服务状态
    service_state: Arc<RwLock<WebServiceState>>,
    /// 请求计数器
    request_counter: Arc<RwLock<u64>>,
    /// 性能监控器
    performance_monitor: Arc<PerformanceMonitor>,
}

/// Web服务状态
#[derive(Debug, Clone, Serialize, Deserialize)]
struct WebServiceState {
    /// 服务是否运行
    is_running: bool,
    /// 启动时间
    start_time: chrono::DateTime<chrono::Utc>,
    /// 总请求数
    total_requests: u64,
    /// 成功请求数
    successful_requests: u64,
    /// 失败请求数
    failed_requests: u64,
    /// 当前并发请求数
    current_concurrent_requests: usize,
    /// 平均响应时间（毫秒）
    avg_response_time_ms: f64,
    /// 最后错误
    last_error: Option<ServiceError>,
}

/// Web API 请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAPIRequest<T> {
    /// 请求ID
    pub request_id: String,
    /// 请求时间戳
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// 请求数据
    pub data: T,
    /// 请求元数据
    pub metadata: RequestMetadata,
}

/// Web API 响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAPIResponse<T> {
    /// 请求ID
    pub request_id: String,
    /// 响应时间戳
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// 响应状态
    pub status: ResponseStatus,
    /// 响应数据
    pub data: Option<T>,
    /// 错误信息
    pub error: Option<ResponseError>,
    /// 响应元数据
    pub metadata: ResponseMetadata,
}

/// 响应状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseStatus {
    /// 状态码
    pub code: u16,
    /// 状态消息
    pub message: String,
    /// 是否成功
    pub success: bool,
}

/// 响应错误
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseError {
    /// 错误代码
    pub code: String,
    /// 错误消息
    pub message: String,
    /// 错误详情
    pub details: Option<String>,
    /// 错误级别
    pub severity: ErrorSeverity,
}

/// 错误严重级别
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorSeverity {
    /// 信息
    Info,
    /// 警告
    Warning,
    /// 错误
    Error,
    /// 严重错误
    Critical,
}

/// 响应元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseMetadata {
    /// 处理时间（毫秒）
    pub processing_time_ms: u64,
    /// 服务版本
    pub service_version: String,
    /// 请求ID
    pub request_id: String,
    /// 附加信息
    pub additional_info: Option<serde_json::Value>,
}

impl<C> OPCUAWebAPIService<C>
where
    C: SemanticConverter + Send + Sync + 'static,
{
    /// 创建新的Web API服务
    pub fn new(converter: C, config: Settings) -> Self {
        Self {
            converter: Arc::new(converter),
            config: config.clone(),
            service_state: Arc::new(RwLock::new(WebServiceState::new())),
            request_counter: Arc::new(RwLock::new(0)),
            performance_monitor: Arc::new(PerformanceMonitor::new()),
        }
    }
    
    /// 启动Web服务
    pub async fn start(&self) -> Result<()> {
        info!("启动OPC UA Web API服务");
        
        // 初始化服务状态
        self.initialize_service_state().await?;
        
        // 创建Warp路由
        let routes = self.create_routes().await?;
        
        // 启动服务器
        let addr = self.config.server.addr().parse()
            .map_err(|e| anyhow!("无效的服务器地址: {}", e))?;
        
        info!("Web服务启动在: {}", addr);
        warp::serve(routes)
            .run(addr)
            .await;
        
        Ok(())
    }
    
    /// 创建路由
    async fn create_routes(&self) -> Result<impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone> {
        // 健康检查端点
        let health_route = warp::path("health")
            .and(warp::get())
            .and_then({
                let service = self.clone();
                move || {
                    let service = service.clone();
                    async move {
                        match service.health_check().await {
                            Ok(health) => Ok::<_, warp::Rejection>(warp::reply::json(&health)),
                            Err(e) => Err(warp::reject::custom(ServiceError::internal_error(e.to_string()))),
                        }
                    }
                }
            });
        
        // 服务信息端点
        let info_route = warp::path("info")
            .and(warp::get())
            .and_then({
                let service = self.clone();
                move || {
                    let service = service.clone();
                    async move {
                        match service.get_service_info().await {
                            Ok(info) => Ok::<_, warp::Rejection>(warp::reply::json(&info)),
                            Err(e) => Err(warp::reject::custom(ServiceError::internal_error(e.to_string()))),
                        }
                    }
                }
            });
        
        // 转换端点
        let convert_route = warp::path("convert")
            .and(warp::post())
            .and(warp::body::json())
            .and_then({
                let service = self.clone();
                move |request: WebAPIRequest<ConversionRequest>| {
                    let service = service.clone();
                    async move {
                        match service.handle_conversion_request(request).await {
                            Ok(response) => Ok::<_, warp::Rejection>(warp::reply::json(&response)),
                            Err(e) => Err(warp::reject::custom(ServiceError::internal_error(e.to_string()))),
                        }
                    }
                }
            });
        
        // 批量转换端点
        let batch_convert_route = warp::path("batch-convert")
            .and(warp::post())
            .and(warp::body::json())
            .and_then({
                let service = self.clone();
                move |request: WebAPIRequest<BatchConversionRequest>| {
                    let service = service.clone();
                    async move {
                        match service.handle_batch_conversion_request(request).await {
                            Ok(response) => Ok::<_, warp::Rejection>(warp::reply::json(&response)),
                            Err(e) => Err(warp::reject::custom(ServiceError::internal_error(e.to_string()))),
                        }
                    }
                }
            });
        
        // 验证端点
        let validate_route = warp::path("validate")
            .and(warp::post())
            .and(warp::body::json())
            .and_then({
                let service = self.clone();
                move |request: WebAPIRequest<ValidationRequest>| {
                    let service = service.clone();
                    async move {
                        match service.handle_validation_request(request).await {
                            Ok(response) => Ok::<_, warp::Rejection>(warp::reply::json(&response)),
                            Err(e) => Err(warp::reject::custom(ServiceError::internal_error(e.to_string()))),
                        }
                    }
                }
            });
        
        // 组合所有路由
        let api_routes = warp::path("api")
            .and(warp::path("v1"))
            .and(
                health_route
                .or(info_route)
                .or(convert_route)
                .or(batch_convert_route)
                .or(validate_route)
            );
        
        // 添加CORS支持
        let cors = warp::cors()
            .allow_any_origin()
            .allow_headers(vec
            .allow_methods(vec;
        
        Ok(api_routes.with(cors))
    }
    
    /// 处理转换请求
    async fn handle_conversion_request(
        &self,
        request: WebAPIRequest<ConversionRequest>,
    ) -> Result<WebAPIResponse<ConversionResult>> {
        let start_time = chrono::Utc::now();
        
        // 更新请求计数
        self.increment_request_count().await;
        self.update_service_state(|state| {
            state.current_concurrent_requests += 1;
            state.total_requests += 1;
        }).await;
        
        let result = self.process_conversion_request(request.data).await;
        
        // 更新服务状态
        self.update_service_state(|state| {
            state.current_concurrent_requests -= 1;
            match &result {
                Ok(_) => state.successful_requests += 1,
                Err(_) => state.failed_requests += 1,
            }
        }).await;
        
        let processing_time = chrono::Utc::now() - start_time;
        self.build_response(request.request_id, result, processing_time).await
    }
    
    /// 处理批量转换请求
    async fn handle_batch_conversion_request(
        &self,
        request: WebAPIRequest<BatchConversionRequest>,
    ) -> Result<WebAPIResponse<BatchConversionResult>> {
        let start_time = chrono::Utc::now();
        
        self.increment_request_count().await;
        self.update_service_state(|state| {
            state.current_concurrent_requests += 1;
            state.total_requests += 1;
        }).await;
        
        let result = self.process_batch_conversion_request(request.data).await;
        
        self.update_service_state(|state| {
            state.current_concurrent_requests -= 1;
            match &result {
                Ok(_) => state.successful_requests += 1,
                Err(_) => state.failed_requests += 1,
            }
        }).await;
        
        let processing_time = chrono::Utc::now() - start_time;
        self.build_response(request.request_id, result, processing_time).await
    }
    
    /// 处理验证请求
    async fn handle_validation_request(
        &self,
        request: WebAPIRequest<ValidationRequest>,
    ) -> Result<WebAPIResponse<ValidationResult>> {
        let start_time = chrono::Utc::now();
        
        self.increment_request_count().await;
        self.update_service_state(|state| {
            state.current_concurrent_requests += 1;
            state.total_requests += 1;
        }).await;
        
        let result = self.process_validation_request(request.data).await;
        
        self.update_service_state(|state| {
            state.current_concurrent_requests -= 1;
            match &result {
                Ok(_) => state.successful_requests += 1,
                Err(_) => state.failed_requests += 1,
            }
        }).await;
        
        let processing_time = chrono::Utc::now() - start_time;
        self.build_response(request.request_id, result, processing_time).await
    }
    
    /// 处理单个转换请求
    async fn process_conversion_request(
        &self,
        request: ConversionRequest,
    ) -> Result<ConversionResult> {
        self.converter.convert(request).await
            .map_err(|e| anyhow!("转换失败: {}", e))
    }
    
    /// 处理批量转换请求
    async fn process_batch_conversion_request(
        &self,
        request: BatchConversionRequest,
    ) -> Result<BatchConversionResult> {
        // 这里需要实现批量转换逻辑
        // 简化实现，实际应使用批量转换管理器
        let mut results = Vec::new();
        
        for conversion_request in request.requests {
            match self.converter.convert(conversion_request).await {
                Ok(result) => results.push(result),
                Err(e) => {
                    error!("批量转换中单个请求失败: {}", e);
                    // 根据配置决定是否继续处理
                    if request.stop_on_error {
                        return Err(anyhow!("批量转换因错误停止: {}", e));
                    }
                }
            }
        }
        
        Ok(BatchConversionResult {
            batch_id: request.batch_id,
            results,
            statistics: Default::default(),
            summary: "批量转换完成".to_string(),
        })
    }
    
    /// 处理验证请求
    async fn process_validation_request(
        &self,
        request: ValidationRequest,
    ) -> Result<ValidationResult> {
        // 这里需要实现验证逻辑
        // 简化实现
        Ok(ValidationResult {
            is_valid: true,
            score: 95.0,
            issues: Vec::new(),
            suggestions: Vec::new(),
            validation_time: chrono::Utc::now(),
        })
    }
    
    /// 构建响应
    async fn build_response<T>(
        &self,
        request_id: String,
        result: Result<T>,
        processing_time: chrono::Duration,
    ) -> Result<WebAPIResponse<T>>
    where
        T: Serialize + Send + Sync,
    {
        match result {
            Ok(data) => {
                Ok(WebAPIResponse {
                    request_id,
                    timestamp: chrono::Utc::now(),
                    status: ResponseStatus {
                        code: 200,
                        message: "成功".to_string(),
                        success: true,
                    },
                    data: Some(data),
                    error: None,
                    metadata: ResponseMetadata {
                        processing_time_ms: processing_time.num_milliseconds() as u64,
                        service_version: env!("CARGO_PKG_VERSION").to_string(),
                        request_id: request_id.clone(),
                        additional_info: None,
                    },
                })
            }
            Err(e) => {
                error!("请求处理失败: {}", e);
                
                Ok(WebAPIResponse {
                    request_id,
                    timestamp: chrono::Utc::now(),
                    status: ResponseStatus {
                        code: 500,
                        message: "内部服务器错误".to_string(),
                        success: false,
                    },
                    data: None,
                    error: Some(ResponseError {
                        code: "INTERNAL_ERROR".to_string(),
                        message: e.to_string(),
                        details: None,
                        severity: ErrorSeverity::Error,
                    }),
                    metadata: ResponseMetadata {
                        processing_time_ms: processing_time.num_milliseconds() as u64,
                        service_version: env!("CARGO_PKG_VERSION").to_string(),
                        request_id: request_id.clone(),
                        additional_info: None,
                    },
                })
            }
        }
    }
    
    /// 健康检查
    async fn health_check(&self) -> Result<HealthStatus> {
        let state = self.service_state.read().await;
        
        Ok(HealthStatus {
            status: if state.is_running { "健康" } else { "不健康" }.to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            uptime_seconds: (chrono::Utc::now() - state.start_time).num_seconds(),
            total_requests: state.total_requests,
            successful_requests: state.successful_requests,
            failed_requests: state.failed_requests,
            current_concurrent_requests: state.current_concurrent_requests,
            avg_response_time_ms: state.avg_response_time_ms,
            last_error: state.last_error.clone(),
        })
    }
    
    // src/services/opcua_webapi.rs (继续)

/// 获取服务信息
async fn get_service_info(&self) -> Result<ServiceInfo> {
    Ok(ServiceInfo {
        name: "OPC UA语义转换服务".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        description: "提供工业物联网数据到OPC UA语义转换的Web API服务".to_string(),
        endpoints: vec,
            "/api/v1/convert".to_string(),
            "/api/v1/batch-convert".to_string(),
            "/api/v1/validate".to_string(),
            "/api/v1/health".to_string(),
        ],
        supported_formats: vec, "XML".to_string()],
        rate_limit: Some(RateLimitInfo {
            requests_per_minute: 1000,
            burst_capacity: 100,
        }),
        authentication_required: true,
        api_version: "v1".to_string(),
        contact_email: Some("support@huawei-opcua-converter.com".to_string()),
        documentation_url: Some("https://docs.huawei-opcua-converter.com".to_string()),
    })
}

/// 初始化服务状态
async fn initialize_service_state(&self) -> Result<()> {
    let mut state = self.service_state.write().await;
    *state = WebServiceState {
        is_running: true,
        start_time: chrono::Utc::now(),
        total_requests: 0,
        successful_requests: 0,
        failed_requests: 0,
        current_concurrent_requests: 0,
        avg_response_time_ms: 0.0,
        last_error: None,
    };
    Ok(())
}

/// 增加请求计数
async fn increment_request_count(&self) {
    let mut counter = self.request_counter.write().await;
    *counter += 1;
}

/// 更新服务状态
async fn update_service_state<F>(&self, updater: F)
where
    F: FnOnce(&mut WebServiceState),
{
    let mut state = self.service_state.write().await;
    updater(&mut state);
}

/// 性能监控器
struct PerformanceMonitor {
    metrics: Arc<RwLock<PerformanceMetrics>>,
    alert_rules: Vec<AlertRule>,
    notification_sender: Option<tokio::sync::mpsc::Sender<AlertNotification>>,
}

/// 性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
struct PerformanceMetrics {
    /// 内存使用（MB）
    memory_usage_mb: f64,
    /// CPU使用率（%）
    cpu_usage_percent: f64,
    /// 响应时间（毫秒）
    response_time_ms: f64,
    /// 吞吐量（请求/秒）
    throughput_rps: f64,
    /// 错误率
    error_rate: f64,
    /// 缓存命中率
    cache_hit_rate: f64,
    /// 连接数
    connection_count: usize,
}

/// 告警规则
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AlertRule {
    /// 规则名称
    name: String,
    /// 指标名称
    metric_name: String,
    /// 阈值
    threshold: f64,
    /// 比较操作符
    operator: ComparisonOperator,
    /// 持续时间（秒）
    duration_seconds: u64,
    /// 告警级别
    severity: AlertSeverity,
    /// 告警消息
    message: String,
}

/// 比较操作符
#[derive(Debug, Clone, Serialize, Deserialize)]
enum ComparisonOperator {
    /// 大于
    GreaterThan,
    /// 大于等于
    GreaterThanOrEqual,
    /// 小于
    LessThan,
    /// 小于等于
    LessThanOrEqual,
    /// 等于
    Equal,
}

/// 告警级别
#[derive(Debug, Clone, Serialize, Deserialize)]
enum AlertSeverity {
    /// 信息
    Info,
    /// 警告
    Warning,
    /// 错误
    Error,
    /// 严重
    Critical,
}

/// 告警通知
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AlertNotification {
    /// 告警ID
    id: String,
    /// 告警标题
    title: String,
    /// 告警消息
    message: String,
    /// 告警级别
    severity: AlertSeverity,
    /// 触发时间
    trigger_time: chrono::DateTime<chrono::Utc>,
    /// 指标值
    metric_value: f64,
    /// 阈值
    threshold: f64,
    /// 建议操作
    suggested_actions: Vec<String>,
}

impl PerformanceMonitor {
    fn new() -> Self {
        Self {
            metrics: Arc::new(RwLock::new(PerformanceMetrics {
                memory_usage_mb: 0.0,
                cpu_usage_percent: 0.0,
                response_time_ms: 0.0,
                throughput_rps: 0.0,
                error_rate: 0.0,
                cache_hit_rate: 0.0,
                connection_count: 0,
            })),
            alert_rules: vec {
        let mut metrics = self.metrics.write().await;
        *metrics = new_metrics;
        self.check_alerts(&metrics).await;
    }
    
    /// 检查告警
    async fn check_alerts(&self, metrics: &PerformanceMetrics) {
        for rule in &self.alert_rules {
            let metric_value = self.get_metric_value(metrics, &rule.metric_name);
            if self.evaluate_rule(metric_value, rule) {
                self.trigger_alert(rule, metric_value).await;
            }
        }
    }
    
    /// 获取指标值
    fn get_metric_value(&self, metrics: &PerformanceMetrics, metric_name: &str) -> f64 {
        match metric_name {
            "memory_usage_mb" => metrics.memory_usage_mb,
            "cpu_usage_percent" => metrics.cpu_usage_percent,
            "response_time_ms" => metrics.response_time_ms,
            "throughput_rps" => metrics.throughput_rps,
            "error_rate" => metrics.error_rate,
            "cache_hit_rate" => metrics.cache_hit_rate,
            "connection_count" => metrics.connection_count as f64,
            _ => 0.0,
        }
    }
    
    /// 评估规则
    fn evaluate_rule(&self, value: f64, rule: &AlertRule) -> bool {
        match rule.operator {
            ComparisonOperator::GreaterThan => value > rule.threshold,
            ComparisonOperator::GreaterThanOrEqual => value >= rule.threshold,
            ComparisonOperator::LessThan => value < rule.threshold,
            ComparisonOperator::LessThanOrEqual => value <= rule.threshold,
            ComparisonOperator::Equal => (value - rule.threshold).abs() < f64::EPSILON,
        }
    }
    
    /// 触发告警
    async fn trigger_alert(&self, rule: &AlertRule, metric_value: f64) {
        if let Some(sender) = &self.notification_sender {
            let notification = AlertNotification {
                id: uuid::Uuid::new_v4().to_string(),
                title: format!("{} 告警", rule.name),
                message: rule.message.clone(),
                severity: rule.severity.clone(),
                trigger_time: chrono::Utc::now(),
                metric_value,
                threshold: rule.threshold,
                suggested_actions: self.get_suggested_actions(rule).await,
            };
            
            let _ = sender.send(notification).await;
        }
    }
    
    /// 获取建议操作
    async fn get_suggested_actions(&self, rule: &AlertRule) -> Vec<String> {
        match rule.metric_name.as_str() {
            "memory_usage_mb" => vec![
                "优化内存使用".to_string(),
                "重启服务".to_string(),
            ],
            "cpu_usage_percent" => vec![
                "增加CPU资源".to_string(),
                "减少并发请求".to_string(),
            ],
            "response_time_ms" => vec![
                "增加缓存".to_string(),
                "升级硬件".to_string(),
            ],
            _ => vec![],
        }
    }
}

// 为Web API服务实现Clone
impl<C> Clone for OPCUAWebAPIService<C>
where
    C: SemanticConverter + Send + Sync + 'static,
{
    fn clone(&self) -> Self {
        Self {
            converter: self.converter.clone(),
            config: self.config.clone(),
            service_state: self.service_state.clone(),
            request_counter: self.request_counter.clone(),
            performance_monitor: self.performance_monitor.clone(),
        }
    }
}